<?php
namespace console\components\task;

use common\models\datas\MessageLog;
use yii\base\BaseObject;
use yii\helpers\Json;

class TimeProcess extends BaseObject
{
    //将param中的时间格式转化成数组
    public  static function transformTime()
    {
        $dimensions = array(
            array(0, 59), //Minutes
            array(0, 23), //Hours
            array(1, 31), //Days
            array(1, 12), //Months
            array(0, 6),  //Weekdays
        );
        $task_time= \Yii::$app->params['taskTime'];
        if (!empty($task_time)) {
            foreach ($task_time as $k => $v) {
                $parameters = preg_split('#\s+#', $v['time'], 5);//array(5) { [0]=> string(2) "10" [1]=> string(1) "*" [2]=> string(1) "*" [3]=> string(1) "*" [4]=> string(1) "*" }
                foreach ($parameters AS $n => &$repeat) {
                    list($repeat, $every) = explode('\\', $repeat, 2) + array(false, 1);
                    if ($repeat === '*') $repeat = range($dimensions[$n][0], $dimensions[$n][1]);
                    else {
                        $repeatPiece = array();
                        foreach (explode(',', $repeat) as $piece) {
                            $piece = explode('-', $piece, 2);
                            if (count($piece) === 2) $repeatPiece = array_merge($repeatPiece, range($piece[0], $piece[1]));
                            else                     $repeatPiece[] = $piece[0];
                        }
                        $repeat = $repeatPiece;
                    }
                    if ($every > 1) foreach ($repeat AS $key => $piece) {
                        if ($piece % $every !== 0) unset($repeat[$key]);
                    }
                }
                $task_time[$k]['format_time'] = $parameters;
                $task_time[$k]['type'] ='timed';
            }
        }
        return $task_time;
    }
//根据当前时间匹配要执行的数组
    public static function filterTime()
    {
        $now = explode(' ', date('i G j n w', time()));//当前时间格式array(5) { [0]=> string(2) "18" [1]=> string(2) "10" [2]=> string(2) "20" [3]=> string(2) "11" [4]=> string(1) "5" }
        $filter_task = self::transformTime();
        if(!empty($filter_task)){
            foreach ($filter_task as $k => $task) {
                foreach ($now AS $key => $piece) {
                    if (!in_array($piece, $task['format_time'][$key])) {
                        unset($filter_task[$k]);
                    }
                }
            }
        }
        if(!empty($filter_task)){
            foreach($filter_task as $k => $task){
                \Yii::$app->swooleClient->send($task);
            }
        }
    }
}